/**
 *  Copyright 2012 Rafal Korytkowski
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.googlecode.rapidjunit.finder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;

import com.googlecode.rapidjunit.RapidJUnit;

/**
 * Searches for JUnits. It looks for JUnit classes that correspond to
 * the given type.
 * 
 * @author Rafal Korytkowski
 */
public class JUnitFinder {

	public IType[] findJUnitsFor(IType testedClass) {
		List<IType> tests = new ArrayList<IType>();

		List<ICompilationUnit> cus = new ArrayList<ICompilationUnit>();
		try {
			IPackageFragmentRoot[] roots = testedClass.getJavaProject()
					.getPackageFragmentRoots();
			IPackageFragment testedClassPF = testedClass.getPackageFragment();
			if (testedClassPF != null) {
				for (IPackageFragmentRoot root : roots) {
					if (!root.isArchive()) {
						IPackageFragment packageFragment = root
								.getPackageFragment(testedClassPF
										.getElementName());
						if (packageFragment.isOpen()) {
							ICompilationUnit[] cusPart = packageFragment
									.getCompilationUnits();
							cus.addAll(Arrays.asList(cusPart));
						}
					}
				}
			}
		} catch (JavaModelException e) {
			RapidJUnit.log(e);
		}

		for (ICompilationUnit cu : cus) {
			if (cu.getElementName().equals(
					testedClass.getElementName().concat("Test.java"))) {
				IType test = cu.findPrimaryType();
				if (test != null) {
					if (JUnitEngine.isJUnit(test)) {
						tests.add(test);
					}
					break;
				}
			}
		}

		return tests.toArray(new IType[0]);
	}
}
